/*
 * RoboEye - Web client for www.newocr.com that allows you
 * to recognize an image captured by the camera.
 *
 * Copyright (C) Oxygen Development, 2011
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package com.devoxy.roboeye.ui.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import com.devoxy.roboeye.R;
import com.devoxy.roboeye.core.FileHelper;
import com.devoxy.roboeye.global.ArrayUtils;
import com.devoxy.roboeye.global.IntentHelper;
import com.devoxy.roboeye.global.PreferencesHelper;
import com.devoxy.roboeye.global.UiHelper;
import com.devoxy.roboeye.ui.DialogHelper;
import com.devoxy.roboeye.ui.NotificationHelper;
import com.devoxy.roboeye.ui.activity.main.RoboEyeActivity;

import java.io.File;

/**
 * Created by Oxygen Development.
 * Author: Dmitriy Tarasov (dm.vl.tarasov@gmail.com)
 * Date: 23.05.11
 * Time: 0:19
 */
public class MainActivity extends RoboEyeActivity {

    private static final int CAMERA_APP = 0;
    private static final int SAVE_TO_FILE_BROWSER = 1;
    private static final int DIRECTORY_FILE_BROWSER = 2;

    private static final String SAVE_TO_TAG = "save_to_tag";
    private static final String LANGUAGE_TAG = "language_tag";
    private static final String ROTATE_TAG = "rotate_tag";

    private String photoFileName;

    private Dialog saveResultDialog;
    private Spinner langSpinner;
    private Spinner rotateSpinner;
    private Button saveTo;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        initProperties(savedInstanceState);
        initBehavior(savedInstanceState);
        initUI(savedInstanceState);

        showSplashScreenIfNeed();
        showAppCrashedIfNeeded();
        showLicenseIfNeed();
    }

    private void showAppCrashedIfNeeded() {
        Boolean needToShow = PreferencesHelper.getPref(R.string.is_app_crashed_pref);
        if (needToShow) {
            Boolean isCrashReportsSwitchedOn = PreferencesHelper.getPref(R.string.crash_reports_pref);
            DialogHelper.appCrashedDialog(this, isCrashReportsSwitchedOn).show();
            PreferencesHelper.setPref(R.string.is_app_crashed_pref, false);
        }
    }

    private void showSplashScreenIfNeed() {
        Boolean isShown = PreferencesHelper.getPref(R.string.is_splash_shown_pref);
        if (!isShown && !PreferencesHelper.isDebug()) {
            Intent splash = IntentHelper.getSplashIntent();
            startActivity(splash);
            PreferencesHelper.setPref(R.string.is_splash_shown_pref, true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.settings:
                startActivity(IntentHelper.getPreferencesIntent());
                return true;

            case R.id.about:
                startActivity(IntentHelper.getAboutIntent());
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CAMERA_APP:
                cameraHandler(resultCode);
                break;

            case SAVE_TO_FILE_BROWSER:
                saveToFileBrowserHandler(resultCode, data);
                break;

            case DIRECTORY_FILE_BROWSER:
                directoryFileBrowserHandler(resultCode, data);
                break;
        }
    }

    private void directoryFileBrowserHandler(int resultCode, Intent data) {
        // TODO check before add new task that directory contains images
        if (resultCode == RESULT_OK) {
            String path = data.getStringExtra(IntentHelper.PATH);
            String language = langSpinner.getSelectedItem().toString();
            String rotate = rotateSpinner.getSelectedItem().toString();
            Intent addTask = IntentHelper.getAddTaskIntent(true, path, path, language, rotate);
            startService(addTask);
        } else if (resultCode == RESULT_CANCELED) {
            NotificationHelper.showText(this, R.string.cancelled);
        }
    }

    private void saveToFileBrowserHandler(int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String path = data.getStringExtra(IntentHelper.PATH);
            saveTo.setText(path);
        } else if (resultCode == RESULT_CANCELED) {
            NotificationHelper.showText(this, R.string.cancelled);
        }
    }

    private void cameraHandler(int resultCode) {
        if (resultCode == RESULT_OK) {
            Boolean autoname = PreferencesHelper.getPref(R.string.autoname_pref);
            if (!autoname) {
                DialogInterface.OnClickListener cancelHandler = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new File(photoFileName).delete();
                        dialog.dismiss();
                    }
                };
                DialogInterface.OnClickListener okHandler = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        EditText text = (EditText) saveResultDialog.findViewById(R.id.value);
                        String textFileName = FileHelper.getTextFilePath(text.getText().toString());
                        addSingleFileTask(textFileName);
                        dialog.dismiss();
                    }
                };
                saveResultDialog = DialogHelper.showEditTextDialog(this,
                        R.string.save_result_of_recognition,
                        R.string.enter_file_name,
                        cancelHandler,
                        okHandler);
                saveResultDialog.show();
            } else {
                addSingleFileTask(FileHelper.getTxtFileName(photoFileName));
            }
        } else if (resultCode == RESULT_CANCELED) {
            NotificationHelper.showText(this, R.string.cancelled);
        }
    }

    private void addSingleFileTask(String textFileName) {
        String language = langSpinner.getSelectedItem().toString();
        String rotate = rotateSpinner.getSelectedItem().toString();
        Intent addTask = IntentHelper.getAddTaskIntent(false, photoFileName, textFileName, language, rotate);
        startService(addTask);
    }

    @Override
    public void initProperties(Bundle bundle) {
        langSpinner = _findViewById(R.id.language);
        rotateSpinner = _findViewById(R.id.rotate);
        saveTo = _findViewById(R.id.save_to);
    }

    @Override
    public void initUI(Bundle bundle) {
        UiHelper.setStringArrayToSpinner(this, R.id.language, R.array.language);
        UiHelper.setStringArrayToSpinner(this, R.id.rotate, R.array.rotate);

        String lang;
        String rotate;

        if (bundle == null) { // get values from preferences
            saveTo.setText(PreferencesHelper.<CharSequence>getPref(R.string.save_to_pref));

            String langValue = PreferencesHelper.getPref(R.string.language_pref);
            String rotateValue = PreferencesHelper.getPref(R.string.rotate_pref);

            lang = ArrayUtils.getDescriptionFromValue(R.array.language, R.array.language_values, langValue);
            rotate = ArrayUtils.getDescriptionFromValue(R.array.rotate, R.array.rotate_values, rotateValue);
        } else { // get values from bundle
            saveTo.setText(bundle.getString(SAVE_TO_TAG));
            lang = bundle.getString(LANGUAGE_TAG);
            rotate = bundle.getString(ROTATE_TAG);
        }
        UiHelper.setSpinnerSelection(this, R.id.language, lang);
        UiHelper.setSpinnerSelection(this, R.id.rotate, rotate);
    }

    @Override
    public void initBehavior(Bundle bundle) {
        View logo = findViewById(R.id.actionbar_logo);
        logo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent about = IntentHelper.getAboutIntent();
                startActivity(about);
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString(SAVE_TO_TAG, saveTo.getText().toString());
        outState.putString(LANGUAGE_TAG, (String) langSpinner.getSelectedItem());
        outState.putString(ROTATE_TAG, (String) rotateSpinner.getSelectedItem());
    }

    private void showLicenseIfNeed() {
        Boolean isShown = PreferencesHelper.getPref(R.string.is_license_shown_pref);
        if (!isShown && !PreferencesHelper.isDebug()) {
            Dialog about = DialogHelper.aboutDialog(this,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            PreferencesHelper.setPref(R.string.is_license_shown_pref, true);
                            dialog.dismiss();
                        }
                    });
            about.show();
        }
    }

    public void photoHandler(View view) {
        photoFileName = FileHelper.getPhotoFileName();
        Intent capturePhoto = IntentHelper.getCaptureIntent(photoFileName);
        if (IntentHelper.isIntentAvailable(capturePhoto)) {
            startActivityForResult(capturePhoto, CAMERA_APP);
        } else {
            NotificationHelper.showText(this, R.string.you_have_not_camera_app);
        }
    }

    public void directoryHandler(View view) {
        Intent i = IntentHelper.getFileBrowserIntent(null);
        startActivityForResult(i, DIRECTORY_FILE_BROWSER);
    }

    public void saveToHandler(View view) {
        Intent i = IntentHelper.getFileBrowserIntent(saveTo.getText());
        startActivityForResult(i, SAVE_TO_FILE_BROWSER);
    }

    public void taskListHandler(View view) {
        Intent i = IntentHelper.getTaskListIntent();
        startActivity(i);
    }

}